package Myfun;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 周斌
 * Date: 2024-06-23
 * Time: 15:44
 */
public class MyThreadPollAdvancedEdition {
    //创建一个任务队列的对象
    public BlockingQueue<Runnable> queue = new ArrayBlockingQueue(1000);
    //创建一个最大线程数
    public  int maxThreadSize = 0;
    //创建一个集合来存储若干个线程
    public List<Thread> threadList = new ArrayList<>();

    //创建构造方法
    public MyThreadPollAdvancedEdition(int corePoolSize, int maxThreadSize) {
       this.maxThreadSize = maxThreadSize;
        for (int i = 0; i < corePoolSize; i++) {
            Thread t = new Thread(()->{
                    try {
                        while (true) {
                            Runnable runnable = queue.take();
                            runnable.run();
                        }
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
            });
            t.start();
            threadList.add(t);
        }
    }
    public void submit(Runnable runnable) throws InterruptedException {
        queue.put(runnable);
        //如果队列中的任务过多，导致线程不够用，可以增加一些线程
        if(queue.size() >=200 && threadList.size() < maxThreadSize) {
           Thread thread = new Thread(()-> {
               try {
                   while(true) {
                       Runnable runnable1 = queue.take();
                       runnable1.run();
                   }
               }
               catch (InterruptedException e) {
                   e.printStackTrace();
               }
           });
           thread.start();
           threadList.add(thread);
        }
    }

    public static void main(String[] args) throws InterruptedException {
        MyThreadPollAdvancedEdition myThreadPollAdvancedEdition = new MyThreadPollAdvancedEdition(10,20);
        for (int i = 0; i < 50000; i++) {
            int id = i;
            myThreadPollAdvancedEdition.submit(new Runnable() {
                @Override
                public void run() {
                    System.out.println("hello " + id + ", " + Thread.currentThread().getName());
                }
            });
        }
    }
}
